package com.zscat.mallplus.service.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zscat.mallplus.cms.entity.CmsSubject;
import com.zscat.mallplus.entity.dto.BusinessReviewReplyDto;
import com.zscat.mallplus.entity.vo.pms.PmsProductConsultInfoVo;
import com.zscat.mallplus.entity.vo.pms.PmsProductReplyInfoVo;
import com.zscat.mallplus.pms.entity.*;
import com.zscat.mallplus.pms.mapper.*;
import com.zscat.mallplus.pms.vo.HomeProductInfo;
import com.zscat.mallplus.service.cms.service.ICmsSubjectService;
import com.zscat.mallplus.service.pms.service.IPmsFavoriteService;
import com.zscat.mallplus.service.ums.service.IUmsMemberService;
import com.zscat.mallplus.sys.mapper.SysStoreMapper;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.vo.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zscat
 * @since 2019-06-15
 */
@Service
public class PmsFavoriteServiceImpl extends ServiceImpl<PmsFavoriteMapper, PmsFavorite> implements IPmsFavoriteService {

    @Resource
    private PmsFavoriteMapper productCollectionRepository;
    @Resource
    private PmsProductMapper productMapper;
    @Resource
    private ICmsSubjectService subjectService;

    @Resource
    private PmsProductReplyMapper pmsProductReplyMapper;

    @Resource
    private PmsProductConsultMapper pmsProductConsultMapper;

    @Resource
    private PmsSkuStockMapper pmsSkuStockMapper;

    @Resource
    private SysStoreMapper storeMapper;
    @Autowired
    private IUmsMemberService memberService;

    @Resource
    private PmsProductPraiseMapper pmsProductPraiseMapper;


    @Override
    public int addProduct(PmsFavorite productCollection) {
        int count = 0;
        productCollection.setMemberId(memberService.getNewCurrentMember().getId());
        PmsFavorite query = new PmsFavorite();
        query.setObjId(productCollection.getObjId());
        query.setMemberId(memberService.getNewCurrentMember().getId());
        query.setType(productCollection.getType());
        PmsFavorite findCollection = productCollectionRepository.selectOne(new QueryWrapper<>(query));
        if (findCollection == null) {
            productCollection.setAddTime(new Date());
            productCollectionRepository.insert(productCollection);
            if (productCollection.getType() == 1) {
                PmsProduct subject = productMapper.selectById(productCollection.getObjId());
                subject.setId(productCollection.getObjId());
                subject.setGiftGrowth(subject.getGiftGrowth() + 1);
                //更新到数据库
                productMapper.updateById(subject);
            }
            if (productCollection.getType() == 2) {
                CmsSubject subject = subjectService.getById(productCollection.getObjId());
                subject.setId(productCollection.getObjId());
                subject.setForwardCount(subject.getForwardCount() + 1);
                //更新到数据库
                subjectService.updateById(subject);
            }

            count = 1;
        } else {
            if (productCollection.getType() == 1) {
                PmsProduct subject = productMapper.selectById(productCollection.getObjId());
                subject.setId(productCollection.getObjId());
                subject.setGiftGrowth(subject.getGiftGrowth() - 1);
                //更新到数据库
                productMapper.updateById(subject);
            }
            if (productCollection.getType() == 2) {
                CmsSubject subject = subjectService.getById(productCollection.getObjId());
                subject.setId(productCollection.getObjId());
                subject.setForwardCount(subject.getForwardCount() - 1);
                //更新到数据库
                subjectService.updateById(subject);
            }
            return productCollectionRepository.delete(new QueryWrapper<>(query));
        }
        return count;
    }


    @Override
    public List<PmsFavorite> listProduct(Long memberId, int type) {
        return productCollectionRepository.selectList(new QueryWrapper<PmsFavorite>().eq("member_id", memberId).eq("type", type).orderByAsc("add_time"));
    }

    @Override
    public List<PmsFavorite> listCollect(Long memberId) {
        return productCollectionRepository.selectList(new QueryWrapper<PmsFavorite>().eq("member_id", memberId).orderByAsc("add_time"));
    }

    @Override
    public PmsProductReply businessReviewReply(UmsMember newCurrentMember, Long id, String content) {
        PmsProductReply pmsProductReply = new PmsProductReply();

        String icon = newCurrentMember.getIcon();
        Long memberId = newCurrentMember.getId();
        String nickname = newCurrentMember.getNickname();

        pmsProductReply.setType(0);
        pmsProductReply.setState(0);
        pmsProductReply.setPic(icon);
        pmsProductReply.setReplyId(id);
        pmsProductReply.setContent(content);
        pmsProductReply.setMemberId(memberId);
        pmsProductReply.setMemberName(nickname);
        pmsProductReply.setCreateTime(System.currentTimeMillis());
        pmsProductReply.setUpdateTime(System.currentTimeMillis());

        pmsProductReplyMapper.insert(pmsProductReply);

        return pmsProductReply;
    }

    @Override
    public CommonResult reviewReplyPraise(Long memberId, Long id, Integer praiseType) {
        CommonResult commonResult = new CommonResult();


        PmsProductConsult pmsProductConsult = pmsProductConsultMapper.selectById(id);

        PmsProductPraise memberPraise = findMemberPraise("reply_id", id, "member_id", memberId);

        if (pmsProductConsult == null) {
            return commonResult.failed("点赞的评论已不存在");
        }

        //点赞
        if (praiseType == 0) {

            PmsProductPraise pmsProductPraise = new PmsProductPraise();

            if (memberPraise != null) {
                return commonResult.failed("你已经点过赞了");
            }

            pmsProductPraise.setState(0);
            pmsProductPraise.setReplyId(id);
            pmsProductPraise.setMemberId(memberId);
            pmsProductPraise.setCreateTime(System.currentTimeMillis());
            pmsProductPraise.setUpdateTime(System.currentTimeMillis());

            pmsProductPraiseMapper.insert(pmsProductPraise);

            Long praise = pmsProductConsult.getPraise();
            praise = praise + 1;

            pmsProductConsult.setPraise(praise);

            pmsProductConsultMapper.updateById(pmsProductConsult);

            return commonResult.success();

        } else {
            //减的时候注意，如果等于0就不要再去减了

            Long praise = pmsProductConsult.getPraise();

            if (memberPraise == null) {
                return commonResult.failed("无法取消点赞");
            }

            pmsProductPraiseMapper.deleteById(memberPraise.getId());

            if (praise > 0) {
                praise = praise - 1;
            }
            pmsProductConsult.setPraise(praise);

            pmsProductConsultMapper.updateById(pmsProductConsult);

            return commonResult.success();
        }
    }

    private PmsProductPraise findMemberPraise(String column, Object value, String column1, Object value1) {
        QueryWrapper<PmsProductPraise> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value).eq(column1, value1);
        return pmsProductPraiseMapper.selectOne(queryWrapper);
    }

    @Override
    public PmsProductConsultInfoVo getReplyInfo(Long id, Long memberId) {
        boolean flag = false;
        PmsProductConsultInfoVo pmsProductConsultInfoVo = new PmsProductConsultInfoVo();

        PmsProductConsult pmsProductConsult = pmsProductConsultMapper.selectById(id);

        if (pmsProductConsult != null) {

            Long skuId = pmsProductConsult.getSkuId();

            PmsSkuStock pmsSkuStock = pmsSkuStockMapper.selectById(skuId);

            if (pmsSkuStock != null) {
                String pic = pmsSkuStock.getPic();

                if (!StringUtils.isEmpty(pic)) {
                    pmsProductConsultInfoVo.setGoodsImg(pic);
                } else {
                    pmsProductConsultInfoVo.setGoodsImg("");
                }
            } else {
                pmsProductConsultInfoVo.setGoodsImg("");
            }

            BeanUtils.copyProperties(pmsProductConsult, pmsProductConsultInfoVo);

            String images = pmsProductConsult.getImages();

            if (!StringUtils.isEmpty(images)) {
                String[] split = images.split(",");
                pmsProductConsultInfoVo.setImages(split);
            } else {
                pmsProductConsultInfoVo.setImages(new String[0]);
            }

            Date consultAddtime = pmsProductConsult.getConsultAddtime();

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");

            pmsProductConsultInfoVo.setConsultAddtime(simpleDateFormat.format(consultAddtime));

            if (pmsProductConsult.getIsanonymous()) {

                String memberName = pmsProductConsult.getMemberName();

                String[] split = memberName.split("");

                String name = split[0] + "*" + "*" + "*" + split[split.length - 1];

                pmsProductConsultInfoVo.setMemberName(name);
            }

            PmsProductReply nodeConsult = findNodeConsult("reply_id", id, "type", 1);

            List<PmsProductReply> pmsProductReplies = findNodeConsult("reply_id", id);


            if (nodeConsult != null) {
                pmsProductConsultInfoVo.setTreasurer(nodeConsult.getContent());
            } else {
                pmsProductConsultInfoVo.setTreasurer("");
            }

            PmsProductPraise memberPraise = findMemberPraise("reply_id", pmsProductConsult.getId(), "member_id", memberId);

            if (memberPraise != null) {
                flag = true;
            }
            pmsProductConsultInfoVo.setIsanonymous(pmsProductConsult.getIsanonymous() == true ? 0 : 1);
            pmsProductConsultInfoVo.setPrice(pmsSkuStock.getPrice());
            pmsProductConsultInfoVo.setCommentNumber(pmsProductReplies.size());
            pmsProductConsultInfoVo.setShareImg(pmsProductConsult.getShareImg());
            pmsProductConsultInfoVo.setIsPraise(flag);

            return pmsProductConsultInfoVo;
        }

        return null;
    }

    @Override
    public PageInfo<PmsProductReplyInfoVo> getReplySonInfo(Long id, Integer pageNum, Integer pageSize) {
        List<PmsProductReplyInfoVo> result = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
        QueryWrapper<PmsProductReply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reply_id", id);
        IPage<PmsProductReply> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNum);
        IPage<PmsProductReply> pmsProductReplyIPage = pmsProductReplyMapper.selectPage(page, queryWrapper);

        List<PmsProductReply> records = pmsProductReplyIPage.getRecords();

        for (PmsProductReply record : records) {
            PmsProductReplyInfoVo pmsProductReplyInfoVo = new PmsProductReplyInfoVo();

            Long createTime = record.getCreateTime();
            Date date = new Date(createTime);

            BeanUtils.copyProperties(record, pmsProductReplyInfoVo);

            pmsProductReplyInfoVo.setCreateTime(simpleDateFormat.format(date));

            result.add(pmsProductReplyInfoVo);

        }


        return new PageInfo<>(pageNum, pageSize, result);

    }


    private PmsProductReply findNodeConsult(String column, Object value, String column1, Object value1) {
        QueryWrapper<PmsProductReply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value).eq(column1, value1);
        return pmsProductReplyMapper.selectOne(queryWrapper);
    }

    private List<PmsProductReply> findNodeConsult(String column, Object value) {
        QueryWrapper<PmsProductReply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value);
        return pmsProductReplyMapper.selectList(queryWrapper);
    }


}
